package lhc.alg.top100;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * description: 迭代与递归解法
 * author: hongchen.liao
 * date:  2022/7/23
 */
public class _230_kth_smallest_element_in_a_bst {

    //迭代解法
    class Solution {
        public int kthSmallest(TreeNode root, int k) {
            Deque<TreeNode> stack = new ArrayDeque<>();
            while(root != null || !stack.isEmpty()){
                while(root != null){
                    stack.push(root);
                    root = root.left;
                }
                root = stack.pop();
                k--;
                if(k == 0 ){
                    break;
                }
                root = root.right;
            }
            return root.val;
        }
    }

    //递归解法
    class Solution2 {
        int rank = 0, res = 0;

        public int kthSmallest(TreeNode root, int k) {
            traverse(root, k);
            return res;
        }

        void traverse(TreeNode root, int k){
            if(root == null){
                return ;
            }
            traverse(root.left, k);

            rank++;
            if(rank == k){
                res = root.val;
                return;
            }
            traverse(root.right, k);
        }

    }


    //Definition for a binary tree node.
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


}
